﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.IO;

namespace IKEA.FileExchange.Security
{
    public class BrightConsultAuthenticationModule : IHttpModule
    {
        private const string CookieName = "FileExchange.Test.AuthCookie";

        #region IHttpModule Members

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
        }

        public static void AddAuthCookie(FileExchangePrincipal principal)
        {
            FileExchangeIdentity identity = (FileExchangeIdentity)principal.Identity;

            LosFormatter formatter = new LosFormatter();

            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, identity);

                ms.Seek(0, SeekOrigin.Begin);

                using (StreamReader sr = new StreamReader(ms))
                {
                    string cookieData = sr.ReadToEnd();

                    HttpCookie authCookie = new HttpCookie(CookieName, cookieData);

                    HttpContext.Current.Response.Cookies.Add(authCookie);
                }
            }   
        }

        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.Cookies[CookieName] != null)
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieName];

                LosFormatter cookieFormatter = new LosFormatter();

                FileExchangeIdentity identity = (FileExchangeIdentity)cookieFormatter.Deserialize(cookie.Value);

                FileExchangePrincipal principal = new FileExchangePrincipal(identity);

                HttpContext.Current.User = principal;
            }
        }

        #endregion
    }
}
